/*
 * @Description: video 模型类
 * @Author: Junhuang
 * @Date: 2022-02-15 11:27:52
 * @LastEditTime: 2022-05-19 11:00:17
 * @LastEditors: Junhuang
 * @Reference:
 */

'use strict';
// 引入
module.exports = app => {
  const { INTEGER, STRING, DATE, TEXT } = app.Sequelize;
  // 配置（重要：一定要配置详细，一定要！！！）
  const Video = app.model.define('video', {
    id: {
      type: INTEGER(20),
      primaryKey: true,
      autoIncrement: true,
    },
    title: {
      type: STRING(100),
      allowNull: false,
      defaultValue: '',
      comment: '视频标题',
    },
    cover: {
      type: STRING,
      allowNull: true,
      defaultValue: '',
      comment: '视频封面',
    },
    category_id: {
      type: INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '分类id',
    },
    user_id: {
      type: INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '用户id',
    },
    duration: {
      type: INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '总时长',
    },
    description: {
      type: TEXT,
      allowNull: false,
      defaultValue: '',
      comment: '视频描述',
    },
    play_count: {
      type: INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '播放量',
    },
    danmu_count: {
      type: INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '弹幕量',
    },
    status: { type: INTEGER, allowNull: false, defaultValue: 0, comment: '状态' },
    created_time: {
      type: DATE,
      // 获取器，对获取的数据库中的字段进行处理，此处将数据库中的时间字段转换为timestamp
      get() {
        const val = this.getDataValue('created_time');
        return (new Date(val)).getTime();
      },
    },
    updated_time: {
      type: DATE,
      // 获取器，对获取的数据库中的字段进行处理，此处将数据库中的时间字段转换为timestamp
      get() {
        const val = this.getDataValue('updated_time');
        return (new Date(val)).getTime();
      },
    },
  }, {
    timestamps: true, // 是否自动写入时间戳
    tableName: 'video', // 自定义数据表名称
    scopes: {
      active: {
        where: {
          status: 1,
        },
      },
    },
  });
  // 关联关系
  Video.associate = function() {
    // 关联作者
    Video.belongsTo(app.model.User, {
      foreignKey: 'user_id',
    });
    // 关联类别
    Video.belongsTo(app.model.Category, {
      foreignKey: 'category_id',
    });
    // 关联视频
    Video.hasMany(app.model.VideoDetail, {
      foreignKey: 'video_id',
      sourceKey: 'id',
    });
  };


  return Video;

};
